var express = require('express');
var router = express.Router();
const { Article, Category, CategoryArticle } = require('../../models');
const { success, fail } = require('../../utils/response');
const { getArticle } = require('../../utils/get-data');
const { NotFoundError, BadRequestError } = require('../../utils/error');
const model = require('../../models/model');

router.get('/', async function(req, res, next) {
  try{
    let {page = 1, limit = 10} = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const offset = (page - 1) * limit;
    const {count, rows: articles} = await Article.findAndCountAll({
      offset,
      limit,
      include: [
        {
          model: Category,
          as: 'categories',
          attributes: {
            exclude: ['createdAt', 'updatedAt'] //排除关联表的字段
          },
          through: {
            attributes: [] //排除中间表字段
          }
        }
      ]
    });
   
    const data = {
      data: articles,
      total: count,
      page,
      limit
    }
    success(res, data, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.get('/:id', async function(req, res, next) {
  try{
    // 分页数据
    let {page = 1, limit = 10} = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const offset = (page - 1) * limit;
    const article = await getArticle(req, res, next);
    const categories = await article.getCategories({ //get + 别名
      order: [['id', 'DESC']],
      limit,
      offset,
      joinTableAttributes: [] //去掉关联表数据
    });
    const count = await article.countCategories() //count + 别名
    success(res, {data: categories, total: count, page, limit}, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.post('/', async function(req, res, next) {
  try{
    const {categoryIds, contentZh, contentEn, slug, titleZh, titleEn, authorId, status, coverimg} = req.body;
    
    if (!Array.isArray(categoryIds) || categoryIds.length === 0) {
      throw new BadRequestError('分类 ID 必须是一个非空数组');
    }
    for (const categoryId of categoryIds) {
      const category = await Category.findByPk(categoryId);
      if (!category) {
        throw new NotFoundError(`分类 ID ${categoryId} 不存在`);
      }
    }
    const article = await Article.create({contentZh, contentEn, slug, titleZh, titleEn, authorId, status, coverimg});
    const categoryArticleRecords = categoryIds.map(categoryId => ({
      categoryId,
      articleId: article.id
    }));
    await CategoryArticle.bulkCreate(categoryArticleRecords);
    success(res, article, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.put('/:id', async function(req, res, next) {
  try{
    const {categoryId, contentZh, contentEn, slug, title, authorId, status, coverimg} = req.body;
    const category = await Category.findByPk(categoryId)
    if(!category){
      throw new NotFoundError('分类不存在')
    }
    const article = await getArticle(req, res, next);
    await article.update({contentZh, contentEn, slug, title, authorId, status, coverimg});
    success(res, article, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.delete('/:id', async function(req, res, next) {
  try{
    const article = await getArticle(req, res, next);
    await article.destroy();
    success(res, null, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
module.exports = router;